/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.core.impl;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.mina.common.IoSession;

import com.cqcis.uip.base.framework.FrameworkConstants;
import com.cqcis.uip.base.framework.common.Task;
import com.cqcis.uip.base.framework.core.RegisteredServiceContext;
import com.cqcis.uip.base.framework.core.SocketClientTaskContextAfterProcessor;
import com.cqcis.uip.base.framework.handlers.TelnetClientService;


/**
 * telnet客户端服务task上下文实现，适配器
 * 
 * @author huangmy
 * @date   2008-8-26
 */
public class TelnetClientTaskContextAdaptor extends AbstractClientTaskContextAdaptor<String> implements TelnetClientService {
	private final static String COUNTER = "COUNTER_" + SocketClientTaskContextAdaptor.class.getName();
	
	@Override
	protected AbstractTaskContext<String> createTaskContext(RegisteredServiceContext serviceContext, Task task) {		
		return new DefaultTelnetClientTaskContext(serviceContext, task);
	}
	
	public void doTextlineReceived(String textline, Task task) throws Exception {
		AtomicLong counter = (AtomicLong)task.getAttribute(COUNTER);
		if (counter == null) {
			counter = new AtomicLong();
			task.setAttribute(COUNTER, counter);
		}
		counter.incrementAndGet();
		
		super.messageSyncReceived(textline, task);
	}
	
	@Override
	protected void notifyCommitEnd(Task task) {
	}
	
	public String doTextlineSend(Task task) throws Exception {		
		return super.messageSyncSend(task);
	}
	
	/**
	 * 正常结束，通过该种方式支持在ClientBlockingService中没有进行任何操作就结束的情况
	 * 
	 */
	@Override
	protected void afterNormalFinished(Task task) {
		IoSession session = task.getSession();
		AtomicLong counter = (AtomicLong)task.removeAttribute(COUNTER);
		SocketClientTaskContextAfterProcessor afterProcessor = (SocketClientTaskContextAfterProcessor)session.getAttribute(FrameworkConstants.SOCKET_CLIENT_TASK_AFTERPROCESSOR);
		if (afterProcessor != null && (counter == null || (counter.get() <= 0))) {
			afterProcessor.afterNormalFinished(task, session);
		}
		super.afterNormalFinished(task); 
	}
}
